package client

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/go-resty/resty/v2"
	"time"
)

// Tvmao 频道名称映射
var mapTvmao = map[string]string{
	"cctv1": "CCTV-CCTV1",
	// 更多键值对...
}

/*
 p值python代码
def sub_req(a, q, id):

	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";


	str1 = "|"+q;
	v = base64.b64encode(str1.encode('utf-8'));

	str2 = id+"|"+a;
	w = base64.b64encode(str2.encode('utf-8'));

	str3 = time.strftime("%w");
	wday = (7 if(int(str3) == 0) else int(str3));
	//print(wday);
	F = _keyStr[wday*wday];


	return (F+str(w,'utf-8')+str(v,'utf-8'));
*/
// p值计算参考python代码
func subReq(a, q, id string) string {
	_keyStr := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
	str1 := "|" + q
	v := base64.StdEncoding.EncodeToString([]byte(str1))

	str2 := id + "|" + a
	w := base64.StdEncoding.EncodeToString([]byte(str2))

	// 获取星期几，并将其转换为 1-7 的格式（星期天为7）
	weekday := time.Now().Weekday()
	wday := int(weekday)
	if weekday == time.Sunday {
		wday = 7
	}

	// 从 _keyStr 中获取对应的字符
	F := string(_keyStr[wday*wday])

	return F + w + v
}

// HandleTvmaoCron 处理 TVMAO 节目单
// TODO 接口失效 待后续处理
// TODO 接口存在反爬虫限制，暂未处理
func HandleTvmaoCron() error {
	fmt.Println("handleTvmaoCron start")
	urlDate := time.Now().Format("20060102")
	fmt.Println(urlDate)
	//source := "tvmao"

	client := resty.New()
	for key, value := range mapTvmao {
		fmt.Printf("Key: %s, Value: %s\n", key, value)
		url := fmt.Sprintf("https://m.tvmao.com/program/%s-w3.html", value)

		resp, err := client.R().
			SetHeaders(map[string]string{
				"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
			}).
			Get(url)

		if err != nil {
			return fmt.Errorf("failed to get data from URL: %v", err)
		}

		doc, err := goquery.NewDocumentFromReader(bytes.NewReader(resp.Body()))
		if err != nil {
			return fmt.Errorf("failed to parse HTML: %v", err)
		}

		var q, a, id string
		doc.Find("form[name='frmq']").Each(func(i int, s *goquery.Selection) {
			q, _ = s.Attr("q")
			a, _ = s.Attr("a")
		})
		doc.Find("input[type='submit']").Each(func(i int, s *goquery.Selection) {
			id, _ = s.Attr("id")
		})

		if q == "" || a == "" || id == "" {
			return fmt.Errorf("failed to find q, a, id attributes")
		}

		p := subReq(a, q, id)
		fmt.Println(a, q, id, p)
		p2 := subReq("9155AF0AF71F33F54D41CCD5B314F649BF", "3517B2A8E1A49C68F341323D484A162C250A7887D5475F609B8316AA00", "E1EACD1C2AFA458FB890A3AEE6F7C12CDB1F9E1F08")
		fmt.Println(p2)
		apiUrl := fmt.Sprintf("https://m.tvmao.com/api/pg?p=%s", p)
		fmt.Println(apiUrl)

		apiResp, err := client.R().
			SetHeaders(map[string]string{
				"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
			}).
			Get(apiUrl)

		if err != nil {
			return fmt.Errorf("failed to get data from API URL: %v", err)
		}

		var data map[string]interface{}
		if err := json.Unmarshal(apiResp.Body(), &data); err != nil {
			return fmt.Errorf("failed to unmarshal JSON: %v", err)
		}

		// 处理返回的数据
		// ...

	}
	return nil
}
